import json
import pandas as pd
import requests as rq
import copy
from coord_convert.transform import wgs2gcj, wgs2bd, gcj2wgs, gcj2bd, bd2wgs, bd2gcj
import time

def main():
    LL = []
    df1 = pd.read_excel('wuhan2.xlsx', sheet_name='Sheet1', encoding='utf-8')
    sheet1(df1)

    df2 = pd.read_excel('wuhan2.xlsx', sheet_name='Sheet2', encoding='utf-8')
    sheet2(df2)

    df3 = pd.read_excel('wuhan2.xlsx', sheet_name='Sheet3', encoding='utf-8')
    sheet3(df3)

def sheet3(df):
    allDialysis = []
    for row in range(0, len(df)):
        d = df.iloc[row]
        thisH = {}

        district = str(d[0]).strip().replace('\n', '').replace(' ', '')
        name = str(d[1]).strip().replace('\n', '').replace(' ', '').split('/')[0]
        status = str(d[3]).strip().replace('\n', '').replace(' ', '')

        if str(d[4]).strip().replace('\n', '') in ['不可','无法手术']:
            brainInfar = -1
            brainInfarSpec = ''
        elif str(d[4]).strip().replace('\n', '') == '可':
            brainInfar = 1
            brainInfarSpec = ''
        else:
            brainInfar = 0
            brainInfarSpec = str(d[4]).strip().replace('\n', '')

        if str(d[5]).strip().replace('\n', '') in ['不可','无法手术']:
            heartInfar = -1
            heartInfarSpec = ''
        elif str(d[5]).strip().replace('\n', '') == '可':
            heartInfar = 1
            heartInfarSpec = ''
        else:
            heartInfar = 0
            heartInfarSpec = str(d[5]).strip().replace('\n', '')

        if str(d[6]).strip().replace('\n', '') in ['不可','无法手术']:
            surgery = -1
            surgerySpec = ''
        elif str(d[6]).strip().replace('\n', '') == '可':
            surgery = 1
            surgerySpec = ''
        else:
            surgery = 0
            surgerySpec = str(d[6]).strip().replace('\n', '')

        detail = str(d[7]).strip().split('\n')[0]
        contact = str(d[9]).strip().replace('\n', '；')

        if row > 29:
            thisH['avail'] = False
        elif status == '未核实':
            thisH['avail'] = False
        else:
            thisH['avail'] = True

        thisH['condition'] = status
        thisH['detail'] = detail
        thisH['tel'] = contact
        thisH['brainInfar'] = brainInfar
        thisH['brainInfar2'] = brainInfarSpec.replace('nan','')
        thisH['heartInfar'] = heartInfar
        thisH['heartInfar2'] = heartInfarSpec.replace('nan','')
        thisH['surgery'] = surgery
        thisH['surgery2'] = surgerySpec.replace('nan','')

        add = parse(name)
        thisH.update(add)

        allDialysis.append(thisH)

    out = {'all': allDialysis}
    with open('wuhan_emergency.json', 'w') as fw:
        fw.write(json.dumps(out, separators=(',', ':'), ensure_ascii=False))

def sheet2(df):
    allDialysis = []
    for row in range(0, len(df)):
        d = df.iloc[row]
        thisH = {}

        district = str(d[0]).strip().replace('\n', '').replace(' ', '')
        name = str(d[1]).strip().replace('\n', '').replace(' ', '').split('/')[0]
        status = str(d[3]).strip().replace('\n', '').replace(' ', '')
        detail = str(d[4]).strip().split('\n')[0]
        contact = str(d[5]).strip().replace('\n', '；')

        if row >= 34:
            thisH['avail'] = False
        elif status == '机位已满':
            thisH['avail'] = False
        else:
            thisH['avail'] = True

        thisH['condition'] = status
        thisH['detail'] = detail
        thisH['tel'] = contact

        add = parse(name)
        thisH.update(add)

        allDialysis.append(thisH)

    out = {'all': allDialysis}
    with open('wuhan_dialysis.json', 'w') as fw:
        fw.write(json.dumps(out, separators=(',', ':'), ensure_ascii=False))

def sheet1(df):
    h = {'all':[]}
    # '急诊（心脑血管、外伤等重症）', '血液透析', '恶性肿瘤（含恶性\n血液病）','儿童（含新生儿）', '孕产妇'
    allTumor = []
    for row in range(0, len(df)):
        d = df.iloc[row]
        thisH = {}

        district = str(d[0]).strip().replace('\n','').replace(' ','')
        name = str(d[1]).strip().replace('\n','').replace(' ','').split('/')[0]
        status = str(d[3]).strip().replace('\n','').replace(' ','')
        detail = str(d[4]).strip().split('\n')[0]
        guidance = str(d[5]).strip().replace('\n','；')
        contact = str(d[6]).strip().replace('\n','；')

        if row >= 6:
            thisH['avail'] = False
        else:
            thisH['avail'] = True

        thisH['condition'] = status
        thisH['detail'] = detail
        if row == 3:
            thisH['detail'] += '；' + guidance
        thisH['tel'] = contact

        add = parse(name)
        thisH.update(add)

        allTumor.append(thisH)

    out = {'all': allTumor}
    with open('wuhan_tumor.json', 'w') as fw:
        fw.write(json.dumps(out, separators=(',', ':'), ensure_ascii=False))

def testing():
    for i in range(0, len(d)):
        d[i] = str(d[i]).replace('\n',';').replace(' ',';')
    city = d[0].strip()
    emg = d[2].strip()
    emgTel = d[3].strip()
    all.append([city, emg, emgTel, ['emg']])

    dia = d[4].strip()
    diaTel = d[5].strip()
    all.append([city, dia, diaTel, ['dia']])

    tumor = d[6].strip()
    tumorTel = d[7].strip()
    all.append([city, tumor, tumorTel, ['tumor']])

    ped = d[8].strip()
    pedTel = d[9].strip()
    all.append([city, ped, pedTel, ['ped']])

    preg = d[10].strip()
    pregTel = d[11].strip()
    all.append([city, preg, pregTel, ['preg']])

    print(len(all))
    i = 0
    while i < len(all):
        # print(i)
        thisHospital = all[i]
        k = 0
        while k < len(all):
            if all[k][1] == all[i][1] and k != i:
                all[i][3].append(all[k][3][0])
                del all[k]
            else:
                k += 1
        i += 1

    print(len(all))
    h = []
    for item in all:
        time.sleep(0.1)
        if item[1] != '/' and item[1] != 'nan':
            print(item)

    out = {'all':h}
    with open('wuhan1.json','w') as fw:
        fw.write(json.dumps(out, separators=(',',':'), ensure_ascii = False))

def parse(name):
    if name.find('(') != -1:
        name = name[name.find('(')]
    h = {}
    url = 'https://restapi.amap.com/v3/place/text?key=de1fb1729e2e4f6fb20d2e6ea3ac8e27' \
        '&keywords=' + name + '&types=090100|090200|090300|090400|090500&city=武汉&children=0&offset=1&page=1&extensions=all'
    response = rq.get(url)
    print(url)
    result = response.json()

    if len(result['pois']) != 0:
        for k, v in result['pois'][0].items():
            if v == []:
                result['pois'][0][k] = ''

        fmt_addr = result['pois'][0]['address']
        fmt_name = result['pois'][0]['name']
        fmt_type1 = result['pois'][0]['type'].split(';')[1]
        fmt_type2 = result['pois'][0]['type'].split(';')[2]
        fmt_alias = result['pois'][0]['alias'].replace('|', '；')
        fmt_district = result['pois'][0]['adname']
        fmt_lng = result['pois'][0]['location'].split(',')[0]
        fmt_lat = result['pois'][0]['location'].split(',')[1]
        fmt_tel = result['pois'][0]['tel']

        newLon, newLat = gcj2wgs(float(fmt_lng), float(fmt_lat))
        h['lng'] = round(newLon, 6)
        h['lat'] = round(newLat, 6)

        h['name_fmt'] = fmt_name
        print(fmt_name)
        h['addr'] = fmt_addr
        h['type1'] = fmt_type1
        h['type2'] = fmt_type2
        h['alias'] = fmt_alias
        h['city'] = result['pois'][0]['cityname']
        h['district'] = fmt_district
        h['tel_gaode'] = fmt_tel

    else:
        h['addr'] = '404'
    return h
    # with open('hubei3.json','w') as fw:
    #     fw.write(json.dumps(h, separators=(',',':'), ensure_ascii=False))
if __name__ == '__main__':
    main()